//
//  CalendarViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/7/23.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import FSCalendar

enum SelectType {
    case single
    case multiple
}

class CalendarViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate, FSCalendarDelegateAppearance {
    
    var selectType: SelectType = .multiple
    
    fileprivate let gregorian = Calendar(identifier: .gregorian)
    fileprivate let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy.MM.dd"
        return formatter
    }()
    
    fileprivate weak var calendar: FSCalendar!
    
    var afterPickDates: ((_ beginDate: String, _ endDate: String?) -> Void)?
    
    // MARK:- Life cycle
    
    override func loadView() {
        
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = UIColor.groupTableViewBackground
        self.view = view
        
        let height: CGFloat = UIDevice.current.model.hasPrefix("iPad") ? 400 : 300
        let calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: height))
        calendar.dataSource = self
        calendar.delegate = self
        if selectType == .multiple {
            calendar.allowsMultipleSelection = true
        } else {
            calendar.allowsMultipleSelection = false
        }
        view.addSubview(calendar)
        self.calendar = calendar
        
        calendar.calendarHeaderView.backgroundColor = UIColor.white
        calendar.calendarWeekdayView.backgroundColor = UIColor.white
        calendar.appearance.eventSelectionColor = UIColor.white
        calendar.appearance.eventOffset = CGPoint(x: 0, y: -7)
        calendar.today = nil // Hide the today circle
        calendar.register(CalendarCell.self, forCellReuseIdentifier: "cell")
        
        calendar.swipeToChooseGesture.isEnabled = true // Swipe-To-Choose
        
        let scopeGesture = UIPanGestureRecognizer(target: calendar, action: #selector(calendar.handleScopeGesture(_:)));
        calendar.addGestureRecognizer(scopeGesture)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = LanguageHelper.getString(key: "CHOOSE_DATE") 
        // For UITest
        self.calendar.accessibilityIdentifier = "calendar"
        
        setBackBarItem()
        
        let rightBt = UIButton()
        rightBt.contentHorizontalAlignment = .right
        rightBt.setImage(UIImage(named: "done"), for: .normal)
        rightBt.tintColor = UIColor.black
        rightBt.addTarget(self, action: #selector(done(_:)), for: .touchUpInside)
        rightBt.sizeToFit()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBt)
        self.navigationItem.rightBarButtonItem?.isEnabled = false
        
    }
    
    func done(_ sender: UIBarButtonItem) {
        let beginDate = self.formatter.string(from: self.calendar.selectedDates.min()!)
        var endDate: String? = nil
        if self.calendar.selectedDates.count > 1 {
            endDate = self.formatter.string(from: self.calendar.selectedDates.max()!)
        }
        if let afterPickDates = afterPickDates {
            afterPickDates(beginDate, endDate)
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK:- FSCalendarDataSource
    
    func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
        let cell = calendar.dequeueReusableCell(withIdentifier: "cell", for: date, at: position)
        return cell
    }
    
    func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
        self.configure(cell: cell, for: date, at: position)
    }
    
    func calendar(_ calendar: FSCalendar, titleFor date: Date) -> String? {
        if self.gregorian.isDateInToday(date) {
            return "今"
        }
        return nil
    }
    
    func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
        return 0
    }
    
    // MARK:- FSCalendarDelegate
    
    func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
        self.calendar.frame.size.height = bounds.height
        //        self.eventLabel.frame.origin.y = calendar.frame.maxY + 10
    }
    
    func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition)   -> Bool {
        return monthPosition == .current
    }
    
    func calendar(_ calendar: FSCalendar, shouldDeselect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool {
        return monthPosition == .current
    }
    
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        if (self.calendar.selectedDates.count > 1 && date < self.calendar.selectedDates[0]) || self.calendar.selectedDates.count > 2 {
            for date in self.calendar.selectedDates {
                self.calendar.deselect(date)
            }
            self.calendar.select(date)
            
        } else {
            var indexDate = self.gregorian.date(byAdding: .day, value: 1, to: self.calendar.selectedDates[0])!
            while indexDate < date {
                self.calendar.select(indexDate)
                indexDate = self.gregorian.date(byAdding: .day, value: 1, to: indexDate)!
            }
        }
        if !(self.navigationItem.rightBarButtonItem?.isEnabled)! {
            self.navigationItem.rightBarButtonItem?.isEnabled = true
        }
        self.configureVisibleCells()
    }
    
    func calendar(_ calendar: FSCalendar, didDeselect date: Date) {
        for sdate in self.calendar.selectedDates {
            if sdate > date {
                self.calendar.deselect(sdate)
            }
        }
        self.calendar.select(date)
        self.configureVisibleCells()
    }
    
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventDefaultColorsFor date: Date) -> [UIColor]? {
        if self.gregorian.isDateInToday(date) {
            return [UIColor.orange]
        }
        return [appearance.eventDefaultColor]
    }
    
    // MARK: - Private functions
    
    private func configureVisibleCells() {
        calendar.visibleCells().forEach { (cell) in
            let date = calendar.date(for: cell)
            let position = calendar.monthPosition(for: cell)
            self.configure(cell: cell, for: date!, at: position)
        }
    }
    
    private func configure(cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
        
        let diyCell = (cell as! CalendarCell)
        // Custom today circle
        diyCell.circleImageView.isHidden = !self.gregorian.isDateInToday(date)
        // Configure selection layer
        if position == .current {
            
            var selectionType = SelectionType.none
            
            if calendar.selectedDates.contains(date) {
                let previousDate = self.gregorian.date(byAdding: .day, value: -1, to: date)!
                let nextDate = self.gregorian.date(byAdding: .day, value: 1, to: date)!
                if calendar.selectedDates.contains(date) {
                    if calendar.selectedDates.contains(previousDate) && calendar.selectedDates.contains(nextDate) {
                        selectionType = .middle
                    }
                    else if calendar.selectedDates.contains(previousDate) && calendar.selectedDates.contains(date) {
                        selectionType = .rightBorder
                    }
                    else if calendar.selectedDates.contains(nextDate) {
                        selectionType = .leftBorder
                    }
                    else {
                        selectionType = .single
                    }
                }
            }
            else {
                selectionType = .none
            }
            if selectionType == .none {
                diyCell.selectionLayer.isHidden = true
                return
            }
            diyCell.selectionLayer.isHidden = false
            diyCell.selectionType = selectionType
            
        } else {
            diyCell.circleImageView.isHidden = true
            diyCell.selectionLayer.isHidden = true
        }
    }
    
}
